<?php
/**
 * @api {post} /Api/Face/ Request 人脸识别别接口
 * @apiName Face
 * @apiGroup Face
 *
 * @apiParam {Number} type 操作类型(必填).
 *
 *  1：查询操作
 *  2：新增人脸操作
 *
 * @apiParam {String} userid  用户id(必填).
 *
 * @apiParam {String} img     img图片转码base64格式(必填).
 *
 * @apiSuccess {Number} code  返回code(大于0为成功).
 *
 * @apiSuccess {Number} phone  手机号码.
 *
 * @apiSuccess {String} msg.
 *
 *  1：人脸查询成功
 *  2：人脸新增成功
 *
 * @apiError {Number} code  返回code.
 *
 * - 1：参数不全
 * - 2：该用户面部不为同一用户
 * - 3：图片重复上传
 * - 4：数据表插入失败
 * - 5：人脸新增失败
 * - 6：人脸查询失败
 * - 7：提交方式错误
 */
/**
 * @api {post} /Api/Face/faceAll/ Request 广告机人脸识别别接口
 * @apiName faceAll
 * @apiGroup Face
 *
 * @apiParam {String} img     img图片转码base64格式(必填).
 *
 */
namespace app\api\controller;
use app\common\controller\Api;
use \think\Log;

class Face extends Api
{
    private $app_id           = "11628985";
    private $app_key          = "DdPPZ3jy3A4NRLyzmMitzvDU";
    private $secret_key       = "5XuKElRcitCqigj4KRfjjx58UK8SEVE0";
    //图片分组
    private $face_group       = "app_test_1";
    //图片类型
    private $face_img_type    = "BASE64";
    //图片质量
    private $quality_control  = "NORMAL";

    public function index()
    {
//         if($this->request->isPOST){
        $result = $this->request->param();
        Log::faceapi('【Face/index】-[data]--'.json_encode($result));
        $data = array();
        if (empty($result['type'])) {
            $return = codemsg(-1);
            Log::faceapi('【Face/index】-[return]--'.json_encode($return));
            echo json_encode($return);die;
        }
        if ($result['type']==1){
            //查询
            $type = 'find';
            $data['img'] = $result['img'];
            // $data['img'] = $this->base64($result['img']);
            $data['userid'] = $result['userid'];
            $data['phone'] = $result['phone'];
        }elseif ($result['type']==2){
            $type = 'add';
            $data['img'] = $result['img'];
            // $data['img'] = $this->base64($result['img']);
            $data['userid'] = $result['userid'];
            $data['phone'] = $result['phone'];
        }else{
            $return = codemsg(-1);
            Log::faceapi('【Face/index】-[return]--'.json_encode($return));
            echo json_encode($return);die;
        }
        $result = $this->Face($type,$data);
        $return = codemsg($result);
        Log::faceapi('【Face/index】-[return]--'.json_encode($return));
        echo json_encode($return);die;
//         }else{
//             $return = codemsg(-7);
//             Log::faceapi('【Face/index】-[return]--'.json_encode($return));
//             echo json_encode($return);die;
//         }

    }

    //广告机人脸识别
    public function faceAll(){
        $result = $this->request->param();
//        $result['img'] = $this->base64('http://p3.so.qhimgs1.com/sdr/200_200_/t01554ab975947d5ca3.jpg');
        Log::faceapi('【Index/faceAll】-[result][参数]--'.json_encode($result));
        if (empty($result['img'])) {
            $return = codemsg(-1);
            Log::faceapi('【Face/faceAll】-[return]--'.json_encode($return));
            echo json_encode($return);die;
        }
        //查询该人脸
        vendor ('face.AipFace');
        $client = new \AipFace($this->app_id, $this->app_key, $this->secret_key);
        $groupId = $this->face_group;
        $imageType = $this->face_img_type;
        $image  = $result['img'];
        $result = $client->search($image, $imageType, $groupId);
        if ($result['result']['user_list']['0']['score'] >=65){
            $return = codemsg(5006);
            Log::faceapi('【Face/faceAll】-[return]--'.json_encode($return));
            echo json_encode($return);die;
        }else{
            $return = codemsg(-7026);
            Log::faceapi('【Face/faceAll】-[return]--'.json_encode($return));
            echo json_encode($return);die;
        }
//        dump($result['result']['user_list']['0']['score']);die;
//        if ($result['error_code'] == 0 && !empty($result['result']['face_token'])){
//            $return = codemsg(5006);
//            Log::faceapi('【Face/faceAll】-[return]--'.json_encode($return));
//            echo json_encode($return);die;
//            $where['open_id'] = array('eq',$result['result']['face_token']);
//            $findface = M('face_openid')->where($where)->find();
//            if($findface){
//                $map['status'] = 1;
//                $map['createtime'] = time();
//                $map['uid'] = $findface['uid'];
//                $map['face_log'] = $result['log_id'];
//                $map['open_id'] = $result['result']['face_token'];
//                $log = M('face_log')->insert($map);
//                if ($log){
//                    $return = codemsg(5006);
//                    Log::faceapi('【Face/faceAll】-[return]--'.json_encode($return));
//                    echo json_encode($return);die;
//                }else{
//                    $return = codemsg(-7027);
//                    Log::faceapi('【Face/faceAll】-[return]--'.json_encode($return));
//                    echo json_encode($return);die;
//                }
//            }else{
//                $return = codemsg(-7026);
//                Log::faceapi('【Face/faceAll】-[return]--'.json_encode($return));
//                echo json_encode($return);die;
//            }
//        }else{
//            $return = codemsg(-7026);
//            Log::faceapi('【Face/faceAll】-[return]--'.json_encode($return));
//            echo json_encode($return);die;
//        }
    }


    /**
     * [Face 人脸识别总函数]
     * @param [string] $type [操作类型]
     * @param [array]  $data [数据]
     */
    public function Face($type,$data){
        Log::faceapi('【Index/Face】-[result.'.$type.'][参数]--'.json_encode($data));
        if (empty($type) || count($data) <= 0 || !is_array($data)) {
            return -1;//参数不全
        }
        //引入人脸注册api
        vendor ('face.AipFace');
        $client = new \AipFace($this->app_id, $this->app_key, $this->secret_key);
        switch ($type) {
            //注册用户
            case 'add':
                //查询是否存在该人脸
                $groupId = $this->face_group;
                $imageType = $this->face_img_type;
                $image  = $data['img'];
                $options["user_id"] = (String)$data['userid'];
                $findface = $client->search($image, $imageType, $groupId,$options);
//                if ($findface['error_code']==0){
//                    if ($data['flag']==1){
//                        return ['code'=>2,'token'=>$findface['result']['face_token']];
//                    }else{
//                        return 2;//人脸新增成功
//                    }
//                }
                //如果该图片人脸不存在
                $result = $this->addUserFace($client,$data);
                Log::faceapi('【Index/Face】-[result.add][新增面部图片]--'.json_encode($result));
                //新增成功
                if ($result['error_code'] == 0) {
                    //图片存储
                    $imginput = $this->base64ToImg($data['img'],$result['result']['face_token']);
                    Log::faceapi('【Index/Face】-[result.imginput][新增面部图片]--'.json_encode($imginput));
                    if ($imginput['code']==1){
                        //判断数据库中是否存在该数据
                        $findopenwhere['open_id'] = array('eq',$result['result']['face_token']);
                        $findopenwhere['uid'] = $data['userid'];
                        $findopen = M('face_openid')->where($findopenwhere)->find();
                        if ($findopen){
                            $del = M('face_openid')->where($findopenwhere)->delete();
                        }
                        //存储数据到数据表
                        $open_id = $result['result']['face_token'];
                        $userId = $data['userid'];
                        //将token存入数据表中
                        $map['open_id'] = $open_id;
                        $map['uid'] = $userId;
                        $map['group'] = $this->face_group;
                        $map['phone'] = $data['phone'];
                        //用户身份
                        if ($data['usertype'] >0){
                            $map['usertype'] = $data['usertype'];
                        }
                        $map['createtime'] = time();
                        Log::faceapi('【Index/Face】-[face_openid.insert]--'.json_encode($map));
                        $insert = M('face_openid')->insert($map);
                        if ($insert == 1) {
                            if ($data['flag']==1){
                                return ['code'=>2,'token'=>$open_id];
                            }else{
                                return 2;//人脸新增成功
                            }
                        }else{
                            $del['userid'] = $userId;
                            $del['openid'] = $open_id;
                            $del = $this->delUserFace($client,$data);
                            return -4;//数据表插入失败
                        }
                    }else{
                        $del['userid'] = $data['userid'];
                        $del['openid'] = $result['result']['face_token'];
                        $del = $this->delUserFace($client,$data);
                        return -5;//人脸新增失败
                    }

                }else{
                    return -5;//人脸新增失败
                }
                break;
            //删除用户
            case 'del':
                return $this->delUserFace($client,$data);
                break;
            //查询用户
            case 'find':
                $return = $this->findUserFace($client,$data);
                if ($return == true) {
                    return 1; //人脸查询成功
                }else{
                    return -6; //人脸查询失败
                }
                break;
            //只通过手机号查询用户
            case 'Phonefind':
                $return = $this->findUserFace($client,$data);
                if ($return == true) {
                    return 1; //人脸查询成功
                }else{
                    return -6; //人脸查询失败
                }
                break;
            //更新用户
            case 'update':
                return $this->updateUserFace($client,$data);
                break;
            //查看用户
            case 'finduser':
                return $this->viewUserFace($client,$data);
                break;
            default:
                return false;
                break;
        }
    }

    /**
     * [viewUserFace 查询用户面部openid等]
     */
    private function viewUserFace($client,$data){
        if (empty($data['userid'])) {
            return false;
        }
        //不存在分组，默认分组
        if (empty($data['group'])) {
            $group = $this->face_group;
        }
        $userId = (String)$data['userid'];
        $return = $client->faceGetlist($userId, $group);
        if ($return['error_code'] != 0) {
            return true;
        }else{
            return $return;
        }

    }

    /**
     * [addUserFace 注册用户人脸识别]
     * @param [array] $client [引入文件api]
     * @param [array] $data   [数据]
     */
    private function addUserFace($client,$data){
        if (empty($data['img']) || empty($data['userid'])) {
            return false;
        }
        //不存在分组，默认分组
        if (empty($data['group'])) {
            $group = $this->face_group;
        }
        $image  = $data['img'];
        $userId = (String)$data['userid'];
        $imageType = $this->face_img_type;
        $options = array();
        $options["quality_control"] = $this->quality_control;
        //调用人脸注册
        return $client->addUser($image, $imageType, $group, $userId,$options);
    }

    /**
     * [delUserFace 删除人脸]
     */
    private function delUserFace($client,$data){
        if (empty($data['userid']) || empty($data['openid'])) {
            return false;
        }
        $userId = (String)$data['userid'];
        //不存在分组，默认分组
        if (empty($data['group'])) {
            $group = $this->face_group;
        }
        $faceToken = $data['openid'];
        // 调用人脸删除
        return $client->faceDelete($userId, $group, $faceToken);
    }

    /**
     * [findUserFace 查询用户人脸识别]
     * @param [array] $client [引入文件api]
     * @param [array] $data   [数据]
     */
    private function findUserFace($client,$data){
        if (empty($data['img']) || empty($data['userid']) || empty($data['name'])) {
            return false;
        }
        //查询是否存在该用户
        $where['phone'] = $data['name'];
        $where['uid'] = $data['userid'];
        $where['group'] = $this->face_group;
        $find = M('face_openid')->where($where)->find();
        Log::faceapi('【Index/findUserFace】--'.json_encode($find));
        if (empty($find)){
            return false;
        }
        $groupId = $this->face_group;
        $imageType = $this->face_img_type;
        $image  = $data['img'];
        $options["user_id"] = (String)$data['userid'];
        $result['result']['user_list'][0]['score'] = 0;
        $result = $client->search($image, $imageType, $groupId, $options);
        Log::faceapi('【Index/findUserFace】-[result]--'.json_encode($result));
        if ($result['error_code'] != 0  ) {
            return false;
        }
        if (count($result['result']['user_list']) <= 0) {
            return false;
        }
        $data = array();
        $data['open_id']  = $result['result']['face_token'];
        $data['face_log'] = $result['log_id'];
        $data['userid']   = $options["user_id"];
        if ($result['result']['user_list'][0]['score'] >=80) {
            //查询日志记录
            $insert = model('FaceOpenid')->face_log($data,1);
            return true;
        }else{
            $insert = model('FaceOpenid')->face_log($data);
            return false;
        }
    }

    /**
     * [findUserFace 查询用户人脸识别手机号面部识别]
     * @param [array] $client [引入文件api]
     * @param [array] $data   [数据]
     */
    public function findPhoneFace($client,$data){

        $groupId = $this->face_group;
        $imageType = $this->face_img_type;
        $image  = $data['img'];
        $options["user_id"] = (String)$data['userid'];
        $result['result']['user_list'][0]['score'] = 0;
        $result = $client->search($image, $imageType, $groupId, $options);
        Log::faceapi('【Index/findUserFace】-[result]--'.json_encode($result));
        if ($result['error_code'] != 0  ) {
            return false;
        }
        if (count($result['result']['user_list']) <= 0) {
            return false;
        }
        $data = array();
        $data['open_id']  = $result['result']['face_token'];
        $data['face_log'] = $result['log_id'];
        $data['userid']   = $options["user_id"];
        if ($result['result']['user_list'][0]['score'] >=80) {
            //查询日志记录
            $insert = model('FaceOpenid')->face_log($data,1);
            return true;
        }else{
            $insert = model('FaceOpenid')->face_log($data);
            return false;
        }
    }

    /**
     * [base64 图片转码]
     */
    public function base64($url){
        if (empty($url)) {
            return false;
        }
        return base64_encode(file_get_contents($url));
    }

    /**
     * [base64ToImg base64转图片]
     */
    public function base64ToImg($img,$token){
        $image = $img;
        $imageName = $token.'.png';
        if (strstr($image,",")){
            $image = explode(',',$image);
            $image = $image[1];
        }
        $path = "./upload/face";
        if (!is_dir($path)){ //判断目录是否存在 不存在就创建
            mkdir($path,0777,true);
        }
        $imageSrc=  $path."/". $imageName;  //图片名字
        Log::faceapi('【Index/base64ToImg】-[result]--'.json_encode($imageSrc));
        $r = file_put_contents($imageSrc, base64_decode($image));//返回的是字节数
//        if (!$r) {
//            return ['data'=>null,"code"=>0,"msg"=>"图片生成失败"];
//        }else{
            return ['data'=>1,"code"=>1,"msg"=>"图片生成成功"];
//        }
    }
}
